
package com.phevos.common.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

public class StringUtil
{

    /**
     * �ַ��滻��
     * 
     * @param inStr String ԭʼ�ַ�
     * @param oldStr String Ҫ�滻������
     * @param newStr String �滻��������
     * @return String �滻֮��õ����ַ�
     */
    public static String replace(String inStr, String oldStr, String newStr)
    {
        if (inStr == null || oldStr == null || newStr == null || oldStr.length() == 0)
        {
            return inStr;
        }
        String resultStr = "";
        int pos = -1;
        boolean exitWhile = false;
        try
        {
            if (inStr != null && !inStr.equals("") && inStr.length() > 0)
            {
                while (!exitWhile)
                {
                    pos = inStr.indexOf(oldStr);
                    if (pos > 0)
                    {
                        resultStr += inStr.substring(0, pos - 0) + newStr;
                        inStr = inStr.substring(pos + oldStr.length());
                    }
                    else if (pos == 0)
                    {
                        resultStr += newStr;
                        inStr = inStr.substring(pos + oldStr.length());
                    }
                    else
                        exitWhile = true;
                }
            }
        }
        catch (Exception e)
        {
            System.out.println("Replacing string:" + inStr + " error, the exception is:" + e);
        }

        return resultStr + inStr;
    }

    /**
     * �滻�׸�ƥ����ַ�
     * 
     * @param inStr String Ҫ�滻������
     * @param oldStr String Ҫ�滻������
     * @param newStr String �滻��������
     * @return String �滻֮��õ����ַ�
     */
    public static String replaceFirst(String inStr, String oldStr, String newStr)
    {
        if (inStr == null || oldStr == null || newStr == null)
        {
            return inStr;
        }
        String resultStr = "";
        int pos = -1;
        pos = inStr.indexOf(oldStr);
        if (pos >= 0)
        {
            resultStr = inStr.substring(0, pos) + newStr
                    + inStr.substring(pos + oldStr.length(), inStr.length());
        }
        return resultStr;
    }

    /**
     * ���List of String ����'A','B','C'�б�
     * 
     * @param list List ��ŵ�List
     * @return String 'A','B','C'���ַ�
     */
    public static String convertListToString(java.util.List list)
    {
        if (list == null)
        {
            return "''";
        }
        java.util.Iterator ir = list.iterator();
        String retStr = "";
        while (ir.hasNext())
        {
            retStr += "'" + ir.next() + "'" + ",";
        }
        if (retStr.endsWith(","))
            retStr = retStr.substring(0, retStr.length() - 1);
        return retStr;
    }

    /**
     * ��str�е�"'"�滻Ϊ"''", Ϊsql���ִ��
     * 
     * @param str
     * @return
     */
    public static String replaceForSQL(String str)
    {
        if (str == null)
            return null;
        return replace(str, "'", "''");
    }

    /**
     * ���ַ���seperator���ֿ����������Ϊ�ջ�մ�,����null
     * 
     * @param s
     * @param seperator
     * @return
     */
    public static String[] convertStringToStringArray(String s, String seperator)
    {
        if (s == null || s.equals(""))
            return null;

        StringTokenizer st = new StringTokenizer(s, seperator);
        Vector vec = new Vector();
        while (st.hasMoreTokens())
        {
            vec.addElement(st.nextToken());
        }
        String[] array = new String[vec.size()];
        vec.copyInto(array);
        return array;
    }

    /**
     * ���ַ�ָ��List
     * 
     * @param s String
     * @param seperator String
     * @return List
     */
    public static List convertStringToArrayList(String s, String seperator)
    {
        if (s == null || s.equals(""))
            return null;

        StringTokenizer st = new StringTokenizer(s, seperator);
        Vector vec = new Vector();
        while (st.hasMoreTokens())
        {
            vec.addElement(st.nextToken());
        }
        String[] array = new String[vec.size()];
        vec.copyInto(array);
        List list = new ArrayList(array.length);
        for (int i = 0; i < array.length; i++)
        {
            list.add(i, array[i]);
        }
        return list;

    }

    /**
     * ���ַ���^�ָ��ArrayList
     * 
     * @param s String
     * @return List
     */
    public static List convertStringToArrayList(String s)
    {
        return convertStringToArrayList(s, "^");
    }

    /**
     * ��List�е��ַ���^l�ӳ��ַ�
     * 
     * @param list List
     * @return String
     */
    public static String convertArrayListToString(List list)
    {
        if (list == null || list.size() == 0)
            return null;

        String s = (String)list.get(0);
        for (int i = 1; i < list.size(); i++)
        {
            s += "^" + (String)list.get(i);
        }
        return s;
    }

    /**
     * ��������ת���� deli �ָ���ַ�
     * 
     * @param arr
     * @param deli
     * @return
     * @post $result!=null
     */
    public static String intArrToString(int[] arr, String deli)
    {
        if (arr == null)
        {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++)
        {
            sb.append(arr[i]);
            if (i != arr.length - 1)
            {
                sb.append(deli);
            }
        }
        return sb.toString();
    }

    /**
     * �� deli �ָ���ַ�ת���������顣
     * 
     * @param s
     * @param deli
     * @return
     * @post $result!=null
     */
    public static int[] stringToIntArr(String s, String deli)
    {
        try
        {
            StringTokenizer tokens = new StringTokenizer(s, deli);
            int[] arr = new int[tokens.countTokens()];
            int idx = 0;
            while (tokens.hasMoreTokens())
            {
                String token = tokens.nextToken();
                int intVal = Integer.parseInt(token);
                arr[idx] = intVal;
                idx++;
            }
            return arr;
        }
        catch (Exception ex)
        {
            return new int[0];
        }
    }

    /**
     * �� deli �ָ���ַ�ת���������顣 ���sΪnull,����s�е��ַ�ת��Ϊ���ֹ�̳��,�򷵻�float[0]
     * 
     * @param s
     * @param deli
     * @return
     * @post $result!=null
     */
    public static float[] stringToFloatArr(String s, String deli)
    {
        try
        {
            StringTokenizer tokens = new StringTokenizer(s, deli);
            float[] arr = new float[tokens.countTokens()];
            int idx = 0;
            while (tokens.hasMoreTokens())
            {
                String token = tokens.nextToken();
                float floatVal = Float.parseFloat(token);
                arr[idx] = floatVal;
                idx++;
            }
            return arr;
        }
        catch (Exception ex)
        {
            return new float[0];
        }
    }

    /**
     * ��"aa^bb^cc"������ַ�ת��Ϊ 'aa','bb','cc'
     * 
     * @author chzhao 2003-03-06
     */
    public static String getInSQL(String str)
    {
        if (str == null)
            return null;
        java.util.StringTokenizer st = new java.util.StringTokenizer(str, "^");
        String tmpStr = "";
        String retStr = "";
        while (st.hasMoreTokens())
        {
            tmpStr = st.nextToken();
            tmpStr = "'" + tmpStr + "'";
            retStr += tmpStr + ",";
        }
        if (retStr != null && retStr.endsWith(","))
            retStr = retStr.substring(0, retStr.length() - 1);
        return retStr;
    }

    /**
     * ��һ��Collection�е�ÿ�������ַ���ʽ��^l����4
     * 
     * @param values ���԰��κζ���
     * @return ת������ַ�
     * @author lvkai 2003/1/17
     */
    public static String convertCollectionToString(Collection values)
    {
        if (values == null || values.size() == 0)
            return "";

        Iterator iterator = values.iterator();
        StringBuffer sb = new StringBuffer(iterator.next().toString());
        while (iterator.hasNext())
        {
            sb.append("^");
            sb.append(iterator.next());
        }
        return sb.toString();
    }

    /**
     * ����^�ָ���ַ��������
     * 
     * @param s String
     * @return String
     */
    public static String sortStringList(String s)
    {
        if (s == null || s.equals(""))
            return s;
        List slist = convertStringToArrayList(s);
        Collections.sort(slist);
        // log(convertArrayListToString(slist));
        return convertArrayListToString(slist);
    }

    /**
     * log
     * 
     * @param s String
     */
    public static void log(String s)
    {
        System.out.println("" + s);
    }

    /**
     * �ж�һ���ַ��Ƿ�Ϊ��,���ַ�Ϊnull����""ʱ
     * 
     * @param s String
     * @return boolean
     */
    public static boolean isEmpty(String s)
    {
        if (s == null || s.equals(""))
            return true;
        else
            return false;
    }

    // public static String[] splitStr(String srcStr, String seperator) {
    // String[] strArray;
    // try {
    // StringTokenizer strToken = new StringTokenizer(srcStr, seperator);
    // int count = strToken.countTokens();
    // strArray = new String[count];
    // // modify by credible_zhang at 2004.07.31:������Ϊ0��ʱ�򷵻�һ��յ��ַ�
    // if(count == 0) return new String[]{""};
    // // modify end.
    // int i = 0;
    // while (strToken.hasMoreElements()) {
    // strArray[i] = strToken.nextToken();
    // i++;
    // }
    // return strArray;
    // }
    // catch (Exception e) {
    // strArray = new String[] {
    // "err"};
    // return strArray;
    // }
    // }
    //
    /**
     * �Էָ���ַ�ָ������
     * 
     * @param srcStr String
     * @param seperator String
     * @return String[]
     */
    public static String[] splitStr(String srcStr, String seperator)
    {
        String[] strArray = null;
        List strArrayList = new ArrayList();
        // ���ָ��seperatorΪ�յ�ʱ����һ��������ַ���ַ�����
        if (seperator == null || seperator.equals(""))
            return new String[]{srcStr};
        // �����ָ��ַ�Ϊ�յ�ʱ�򷵻�һ����"err"���ַ�����
        if (srcStr == null)
            return new String[0];
        int sepLen = seperator.length();
        int start = 0;
        int end = srcStr.indexOf(seperator, start);
        while (end != -1)
        {
            String temp = srcStr.substring(start, end);
            strArrayList.add(temp);
            start = end + sepLen;
            end = srcStr.indexOf(seperator, start);
        }
        String temp = srcStr.substring(start, srcStr.length());
        strArrayList.add(temp);
        return (String[])strArrayList.toArray(new String[strArrayList.size()]);
    }

    /**
     * �ָ��ַ�Ϊ���飬����ÿ��Ԫ�ض�ȥ��ǰ��ͺ���Ŀո�
     * 
     * @param str
     * @return
     */
    public static String[] splitStrWithTrim(String srcStr, String seperator)
    {
        String[] strArray = null;
        List strArrayList = new ArrayList();
        // ���ָ��seperatorΪ�յ�ʱ����һ��������ַ���ַ�����
        if (seperator == null || seperator.equals(""))
            return new String[]{srcStr};
        // �����ָ��ַ�Ϊ�յ�ʱ�򷵻�һ����"err"���ַ�����
        if (srcStr == null)
            return new String[0];
        int sepLen = seperator.length();
        int start = 0;
        int end = srcStr.indexOf(seperator, start);
        while (end != -1)
        {
            String temp = srcStr.substring(start, end);
            temp.trim();
            temp = trimLeft(temp);
            strArrayList.add(temp);
            start = end + sepLen;
            end = srcStr.indexOf(seperator, start);
        }
        String temp = srcStr.substring(start, srcStr.length());
        temp.trim();
        temp = trimLeft(temp);
        strArrayList.add(temp);
        return (String[])strArrayList.toArray(new String[strArrayList.size()]);
    }

    /**
     * �Կո�str�ָ������ ��strΪnullʱ�����㳤�ȵ�����
     * 
     * @param str
     * @return
     */
    public static String[] splitStr(String str)
    {
        if (str == null)
        {
            return new String[0];
        }
        StringTokenizer st = new StringTokenizer(str, " ");
        List list = new ArrayList();
        while (st.hasMoreTokens())
        {
            list.add(st.nextToken().trim());
        }
        return (String[])list.toArray(new String[list.size()]);
    }

    /**
     * �Գ��ȷָ��ַ�,�ָ������
     * 
     * @param content StringBuffer
     * @param length int
     * @return String[]
     */
    public static String[] splitStr(StringBuffer content, int length)
    {
        if (content == null)
        {
            return null;
        }
        else if (content.length() <= length)
        {
            return new String[]{content.toString()};
        }
        else
        {
            int arraySize = (int)Math.ceil(content.length() / (float)length);
            String[] strings = new String[arraySize];
            for (int i = 0; i < arraySize; i++)
            {
                int start = i * length;
                int end = (i + 1) * length <= content.length() ? (i + 1) * length : content
                        .length();
                strings[i] = content.substring(start, end);
            }
            return strings;
        }
    }

    /**
     * ���ַ�����ϲ����� seprator �ָ��һ���ַ�
     * 
     * @param srcArr
     * @param seperator
     * @return String
     */
    public static String mergStr(String[] srcArr, String seperator)
    {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; srcArr != null && i < srcArr.length; i++)
        {
            sb.append(srcArr[i]);
            if (i != srcArr.length - 1)
            {
                sb.append(seperator);
            }
        }
        return sb.toString();
    }

    /**
     * �ַ�ת�� ISO TO GBK
     * 
     * @param str
     * @return
     */
    public static String iso2gbk(String str)
    {
        String value = "";
        if (str == null || str.length() == 0)
            return "";
        try
        {
            value = new String(str.getBytes("ISO8859_1"), "GBK");
        }
        catch (Exception e)
        {
            return null;
        }
        return value;

    }

    /**
     * �ַ�ת�� GBK TO ISO
     * 
     * @param str
     * @return
     */
    public static String gbk2iso(String str)
    {
        String value = "";
        if (str == null || str.length() == 0)
            return "";
        try
        {
            value = new String(str.getBytes("GBK"), "ISO8859_1");
        }
        catch (Exception e)
        {
            return null;
        }
        return value;

    }

    /**
     * ɾ���ַ��еĿո�
     * 
     * @param s String
     * @return String
     */
    public static String removeSpaces(String s)
    {
        if (s == null)
        {
            return s;
        }
        StringBuffer sb = new StringBuffer();
        int length = s.length();
        for (int i = 0; i < length; i++)
        {
            char c = s.charAt(i);
            if (!Character.isWhitespace(c))
            {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * ���ַ��еĿհ��ַ��������ַ��滻
     * 
     * @param s
     * @param replace
     * @return
     */
    public static String removeSpaces(String s, String replace)
    {
        if (s == null)
        {
            return s;
        }
        StringBuffer sb = new StringBuffer();
        int length = s.length();
        for (int i = 0; i < length; i++)
        {
            char c = s.charAt(i);
            if (!Character.isWhitespace(c))
            {
                sb.append(c);
            }
            else
            {
                sb.append(replace);
            }
        }
        return sb.toString();
    }

    /**
     * ����һ���ַ��а����ַ�ĸ���
     * 
     * @param str String
     * @param sub String
     * @return int
     */
    public static int containSubstring(String str, String sub)
    {
        if (str == null || sub == null)
        {
            return 0;
        }
        int count = 0;
        boolean run = true;
        do
        {
            int index = str.indexOf(sub);
            if (index == -1)
            {
                run = false;
            }
            else
            {
                count++;
                str = str.substring(index + sub.length(), str.length());
            }
        }
        while (run);
        return count;
    }

    /**
     * �Ƚ�}�������Ƿ����
     * 
     * @param a
     * @param b
     * @return
     */
    public static boolean compareStringArray(String[] a, String[] b)
    {
        if (a == null || b == null)
        {
            return !((a == null) ^ (b == null));
        }
        if (a.length != b.length)
        {
            return false;
        }
        for (int i = 0; i < a.length; i++)
        {
            if (a[i] == null || b[i] == null)
            {
                if ((a[i] == null) ^ (b[i] == null))
                {
                    return false;
                }
            }
            else if (!a[i].equals(b[i]))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * ���ָ�����±��ж�}�������Ƿ���ȣ���ȷ���true�����򷵻�false
     * 
     * @param a ���ڱȽϵĵ�һ������
     * @param b ���ڱȽϵĵڶ�������
     * @param c ���ڱȽϵ��±�����
     * @return true/false
     */
    public static boolean compareStringArray(String[] a, String[] b, int[] c)
    {
        if (c == null || c.length == 0)
        {
            return true;
        }
        if (a == null || b == null || a.length < c.length || b.length < c.length)
        {
            return false;
        }
        for (int i = 0; i < c.length; i++)
        {
            if ((a[i] == null) && (b[i] == null))
            {
                continue;
            }
            if ((a[i] == null) || (b[i] == null))
            {
                return false;
            }
            if (!a[i].equals(b[i]))
            {
                return false;
            }
        }
        return true;
    }

    /**
     * ��һ���ַ��ʾ����ֵ���ȡ����
     * 
     * @param s
     * @param decimalDigits
     * @return
     * @author wangmh
     */
    public static String truncNumberString(String s, int decimalDigits)
    {
        if (s == null || decimalDigits < 0)
        {
            return s;
        }
        else
        {
            s = s.trim();
        }
        int pointIdx = s.indexOf(".");
        if (s.length() == 0 || pointIdx == -1)
        {
            return s;
        }
        int endIdx = s.length();
        if (decimalDigits == 0)
        {
            endIdx = Math.min(endIdx, pointIdx);
        }
        else
        {
            endIdx = Math.min(endIdx, pointIdx + decimalDigits + 1);
        }
        return s.substring(0, endIdx);
    }

    /**
     * ��str���begin,end���Ϊ����ַ�����
     * 
     * @param str
     * @param b - begin String
     * @param e - end String
     * @return
     */
    public static String[] getValueFromString(String str, String b, String e)
    {
        int size = containSubstring(str, b);
        String[] ret = new String[size];
        int index = 0;
        int t;
        int step = b.length();
        for (int i = 0; i < size; i++)
        {
            index = str.indexOf(b, index);
            t = str.indexOf(e, index);
            ret[i] = str.substring((index = index + step), t);
        }
        return ret;
    }

    /**
     * �ж�һ���ַ��Ƿ������ȷת������������
     * 
     * @param str String
     * @return boolean
     */
    public static boolean isIntNumber(String str)
    {
        if (str == null)
        {
            return false;
        }
        else
        {
            str = str.trim();
            for (int i = 0, length = str.length(); i < length; i++)
            {
                if (!Character.isDigit(str.charAt(i)))
                {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * �ж�String�������Ƿ�Ϊ��������,������ֻ�������һ��'.'
     * 
     * @param str String
     * @return boolean
     */
    public static boolean isDoubleNumber(String str)
    {
        int p = 0;
        if (str == null)
        {
            return false;
        }
        else
        {
            str = str.trim();
            for (int i = 0, length = str.length(); i < length; i++)
            {
                if (!Character.isDigit(str.charAt(i)))
                {
                    if (str.charAt(i) != '.')
                        return false;
                    else
                        p++;
                }
            }
            if (p > 1)
                return false;
            return true;
        }
    }

    // public static void main(String[] args){
    // String[] ret = getValueFromString("<123><acd>x<fff> <6666>","<",">");
    // for(int i = 0; i < ret.length; i++){
    // System.out.println(ret[i]);
    // }
    // }

    /**
     * ɾ�����l��Ŀո�
     * 
     * @param value
     * @return
     */
    public static String trimLeft(String value)
    {
        String result = value;
        if (result == null)
            return result;
        char ch[] = result.toCharArray();
        int index = -1;
        for (int i = 0; i < ch.length; i++)
        {
            if (Character.isWhitespace(ch[i]))
            {
                index = i;
            }
            else
            {
                break;
            }
        }
        if (index != -1)
        {
            result = result.substring(index + 1);
        }
        return result;
    }

    /**
     * ����֪�Ļ�֪��ʽ��Stringת����double ת���ĸ�ʽΪ:"19873","198.73","1,987.3"...
     * ����������ϸ�ʽ���ַ�򽫴��з����ֵ��ַ�����4ת��Double����� java.long.NumberFormatException.
     * �ڴ˷���������ǽ������ָ�ʽ���ַ�ת����Double.parserDouble()��������ʶ��� ��ʽ.����:��װ������AIX��ps�е�pcpuֵΪ"0,2"��0.2
     * 
     * @param value String
     * @return double
     */
    public static double parserDouble(String value)
    {
        String temp = "0.0";
        if (value != null)
        {
            int commaNum = containSubstring(value, ",");
            int dotNum = containSubstring(value, ".");
            if (commaNum >= 1 && dotNum == 1)
                temp = value.replaceAll(",", "");
            else if (commaNum == 1 && dotNum == 0)
            {
                temp = value.replaceAll(",", ".");
            }
            else
                temp = value;
        }
        return Double.parseDouble(temp);
    }

    /**
     * �Էǿ�ѧ�����ʽ������ת��Ϊ�ַ�
     * 
     * @param d double
     * @return String
     */
    public static String getString(double d)
    {
        String str = "";
        double max = 1000000d;
        int cnt = 0;
        while (d >= max)
        {
            d /= max;
            cnt++;
        }
        str = String.valueOf(d);
        int index = str.indexOf('.');
        String s = str.substring(0, index);
        int l = str.length();
        int idx = index + 1 + cnt * 6;
        if (l > idx)
        {
            s += str.substring(index + 1, idx);
            s += ".";
            s += str.substring(index + 1 + cnt * 6);
        }
        else
        {
            s += str.substring(index + 1);
            for (int i = 0; i < idx - l; i++)
            {
                s += "0";
            }
        }
        if (s.endsWith(".0"))
        {
            s = s.substring(0, s.length() - 2);
        }
        return s;
    }

    /**
     * ��ȡbyte������length֮�ڵ��ַ�
     * 
     * @param str String
     * @param length int
     * @return String
     */
    public static String interceptByByteLength(String str, int length)
    {
        int bytes;
        while ((bytes = str.getBytes().length) > length)
        {
            int l = (int)Math.ceil((bytes - length) / 2.0);
            str = str.substring(0, str.length() - l);
        }
        return str;
    }

    /**
     * ����
     * 
     * @param args String[]
     */
    public static void main(String[] args)
    {
        String str = "aaa����1234";
        System.out.println("" + interceptByByteLength(str, 4));
    }
}
